from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.db.models import Q


def read(request):
    ret = models.UserInfo.objects.all().values_list()
    lst1 = []
    for i in ret:
        lst = list(i)
        lst.insert(4, i[3].strftime("%Y-%m-%d"))
        lst.pop(3)
        lst1.append(lst)
    return render(request, 'read.html', {'lst1': lst1})


def add(request):
    if request.method == 'GET':
        return render(request, 'add.html')
    else:
        # name_new = request.POST.get('name')
        # price_new = request.POST.get('price')
        # data_new = request.POST.get('data')
        # press_new = request.POST.get('press')
        models.UserInfo.objects.create(
            # name=name_new,
            # price=price_new,
            # data=data_new,
            # press=press_new
            **(request.POST.dict())
        )
        # return HttpResponse('添加成功！')
        return render(request, 'add_complete.html')


def add_complete(request):
    return render(request, 'add_complete.html')


def dele(request, n):
    models.UserInfo.objects.filter(id=n).delete()
    return redirect('read')


def modify(request, id1, name, price, data, press):
    if request.method == 'GET':
        return render(request, 'modify.html', {'id': id1, 'name': name, 'price': price, 'data': data, 'press': press})
    else:
        models.UserInfo.objects.filter(id=id1).update(
            **(request.POST.dict())
        )
        return redirect('read')


def exe(request):
    # 查询某某出版社出版过的价格大于200的书籍
    # ret = models.UserInfo.objects.filter(price__gt=200)
    # for i in ret:
    #     print(i.name)

    # 查询2017年8月出版的所有以py开头的书籍名称
    # ret = models.UserInfo.objects.filter(data__year=2017, data__month=8, name__startswith='py')
    # for i in ret:
    #     print(i.name)

    # 查询价格为50, 100或者150的所有书籍名称及其出版社名称
    # ret = models.UserInfo.objects.filter(Q(price=50) | Q(price=100) | Q(price=150))
    # for i in ret:
    #     print(i.name, i.press)

    # 查询价格在100到200之间的所有书籍名称及其价格
    # ret = models.UserInfo.objects.filter(price__range=[100, 200])
    # for i in ret:
    #     print(i.name, i.price)

    # 查询所有人民出版社出版的书籍的价格（从高到低排序，去重）
    ret = models.UserInfo.objects.values('press', 'price').order_by('price').reverse().distinct()
    for i in ret:
        print(i['press'], i['price'])

    return HttpResponse('查找成功！')

